
latin := function (n)

	local a1, valid3Sets, sizeOf3Set, innerIndex, i, outerSize, diIndex,a2, Latinsquares,k;
	a1 := Arrangements([1..n],n-1);
	sizeOf3Set := n-1;
	outerSize := Factorial(n);

	i := 1;
	while i <= outerSize do 
		innerIndex := 1;
		while innerIndex <= sizeOf3Set do
			if a1[i][innerIndex] = innerIndex+1 then
				Unbind(a1[i]);
				break;
			fi; 
			innerIndex := innerIndex+1;	
		od;
		i := i + 1; 
	od;
        a1:=Set(a1);
        a1:=Arrangements(a1,n-1);
 	i:=1;
	outerSize:= Length(a1);
	while i <= outerSize do 
		innerIndex:=1;
		while innerIndex <= sizeOf3Set do
			if innerIndex+1 in a1[i][innerIndex] then
				Unbind(a1[i]);
				break;
			fi;
			innerIndex := innerIndex + 1;
		od;
		i := i + 1;
	od; 
####################
	a1:=Set(a1);
        a2:=[1..n-1];
	i:=1;
	outerSize:= Length(a1);
	while i <= outerSize do 
		innerIndex:=1;
		while innerIndex <= sizeOf3Set do
			diIndex:=1;
			while diIndex <= n-1 do
				a2[diIndex]:=a1[i][diIndex][innerIndex];
				diIndex:=diIndex+1;
				od;
					a2:=Set(a2);
 					if Length(a2)=n-1 then innerIndex := innerIndex + 1;  else 	Unbind(a1[i]);
					break;
					fi;


			innerIndex := innerIndex + 1;
		od;
		i := i + 1;
	od; 

	a1:=Set(a1);
	k:=Length(a1);
 	Latinsquares:= Factorial(n)*Factorial(n-1)*k;



	return Latinsquares;

         
end;


